//
//  ATMInfoHelper.m
//  ATMAssistant
//
//  Created by admin  on 2017/6/13.
//  Copyright © 2017年 admin . All rights reserved.
//

#import "ATMInfoHelper.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "YYModel.h"

@protocol ATMInfoHelperExports <JSExport>

JSExportAs(userList,    - (NSString *)userListWithargs:(NSArray *)args);
JSExportAs(openAp,      - (void)openAp:(NSString *)bundleID args:(NSArray *)args);
JSExportAs(isFirst,     - (NSString *)isFirstithID:(NSString *)ID args:(NSArray *)args);
JSExportAs(isInstalled, - (NSString *)isInstalledID:(NSString *)ID args:(NSArray *)args);

@end

@interface ATMInfoHelper ()<ATMInfoHelperExports>

@end

//0.@"LSApplicationWorkspace"
//1.@"defaultWorkspace"
//2.@"allInstalledApplications"
//3.@"bundleType"
//4.@"bundleIdentifier"
//5.@"localizedName"
//6.@"applicationProxyForIdentifier:"
//7.@"isInstalled"
//8.@"registeredDate"
//9.@"containerURL"
//10.@"openApplicationWithBundleID:"
//11.@"LSApplicationProxy"

#define kAppWorkSpaceClz     NSClassFromString(args[0])
#define kAppWorkDef          NSSelectorFromString(args[1])
#define kAppInstalled        NSSelectorFromString(args[2])
#define kBDType              NSSelectorFromString(args[3])
#define kBDID                NSSelectorFromString(args[4])
#define kAppLocalizedName    NSSelectorFromString(args[5])
#define kAppProxyByID        NSSelectorFromString(args[6])
#define kAppIsInstalled      NSSelectorFromString(args[7])
#define kAppRegisteredDate   NSSelectorFromString(args[8])
#define kAppContainerURL     NSSelectorFromString(args[9])
#define kAppOpenWithID       NSSelectorFromString(args[10])
#define kAppProxyClz         NSClassFromString(args[11])

@implementation ATMInfoHelper

+ (instancetype)shareInstance
{
    static ATMInfoHelper *infoHelper;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        infoHelper = [ATMInfoHelper new];
    });
    
    return infoHelper;
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"

- (NSString *)userListWithargs:(NSArray *)args
{
    NSMutableArray *userList = [NSMutableArray array];
    @try {
        NSArray *items = [[kAppWorkSpaceClz performSelector:kAppWorkDef] performSelector:kAppInstalled];
        
        for (id item in items)
        {
            NSString *bundleType = [item performSelector:kBDType];
            if ([[bundleType lowercaseString] containsString:@"user"])
            {
                NSString *bundleID = [item performSelector:kBDID];
                NSString *appName = [item performSelector:kAppLocalizedName];
                
                ATMAp *ap = [ATMAp new];
                ap.bundleid = bundleID;
                ap.appname = appName;
                [userList addObject:ap];
            }
        }
    } @catch (NSException *exception) {
        
    } @finally {
        return [userList yy_modelToJSONString];
    }
}

- (NSString *)isFirstithID:(NSString *)ID args:(NSArray *)args
{
    ATMAp *ap = [self apWithID:ID args:args];
    NSTimeInterval installedTime =  [ap.itime floatValue];
    NSTimeInterval nowTime = [[NSDate date] timeIntervalSince1970];
    NSTimeInterval duration = nowTime - installedTime;
    if (duration > 0 && duration < 60 * 60 * 12) {
        return @"1";
    }
    
    return @"0";
}

- (NSString *)isInstalledID:(NSString *)ID args:(NSArray *)args
{
    ATMAp *ap = [self apWithID:ID args:args];
    return  [ap.isInstalled isEqualToString:@"1"] ? @"1":@"0";
}

- (ATMAp *)apWithID:(NSString *)ID args:(NSArray *)args
{
    ATMAp *atm = [ATMAp new];

    @try {
        atm.bundleid = ID;
        
        if (![ID isKindOfClass:[NSString class]] || ID.length == 0)
        {
            atm.isInstalled = @"0";
            return atm;
        }
        
        id appProxy = [kAppProxyClz performSelector:kAppProxyByID withObject:ID];
        if (![appProxy performSelector:kAppIsInstalled])
        {
            atm.isInstalled = @"0";
            return atm;
        }
        
        //iOS 10
        SEL registeredDateSEL = kAppRegisteredDate;
        if ([appProxy respondsToSelector:registeredDateSEL])
        {
            NSDate *registeredDate = [appProxy performSelector:registeredDateSEL];
            atm.appname = [appProxy performSelector:kAppLocalizedName];;
            atm.itime = [NSString stringWithFormat:@"%f",[registeredDate timeIntervalSince1970]];
            atm.isInstalled = @"1";
        }
        else
        {
            NSString *bundleIDSanboxHomeDirectory = [[appProxy performSelector:kAppContainerURL] path];
            if ([[NSFileManager defaultManager] fileExistsAtPath:bundleIDSanboxHomeDirectory])
            {
                NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:bundleIDSanboxHomeDirectory error:nil];
                if ([fileAttributes objectForKey:NSFileCreationDate])
                {
                    NSTimeInterval itime = [[fileAttributes objectForKey:NSFileCreationDate] timeIntervalSince1970];
                    atm.appname = [appProxy performSelector:kAppLocalizedName];;
                    atm.itime = [NSString stringWithFormat:@"%f",itime];
                    atm.isInstalled = @"1";
                }
            }
        }
    } @catch (NSException *exception) {
    } @finally {
        return atm;
    }
}

- (void)openAp:(NSString *)bundleID args:(NSArray *)args
{
    @try {
        if ([bundleID isKindOfClass:[NSString class]])
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[kAppWorkSpaceClz performSelector:kAppWorkDef] performSelector:kAppOpenWithID withObject:[bundleID copy]];
            });
        }
    }
    @catch (NSException *exception) {}
    @finally {}
}

#pragma clang diagnostic pop
#pragma clang diagnostic pop

@end
